import hashlib
import os
import uuid

from django.conf import settings
from django.http import JsonResponse

from Detection.utils.utils import read_part_wavefile
from PatientRecord.models import PatientRecord
from .models import AudioRecord


# 获得随机的照片名字
def get_random_str():
    uuid_val = uuid.uuid4()
    uuid_str = str(uuid_val).encode('utf-8')
    md5 = hashlib.md5()
    md5.update(uuid_str)
    return md5.hexdigest()


# 上传音频文件
def UploadAudio(request):
    if request.method == 'GET':
        result = {'code': 400, 'error': '上传音频方式错误'}
        return JsonResponse(result)
    else:
        audio_file = request.FILES.get('audio')
        username = request.POST.get('username')
        suffix = os.path.splitext(audio_file.name)[1]
        file_type = suffix[1:]
        if file_type != "wav" or not username:
            return JsonResponse({'code': 400, 'msg': '音频文件上传错误'})

        audio_name = get_random_str()  # 随机生成一个图片的名称
        file_path = os.path.join(settings.MEDIA_ROOT, audio_name + suffix)

        try:
            f = open(file_path, 'wb')
            for data_block in audio_file.chunks():
                f.write(data_block)
            f.close()

            record = AudioRecord.objects.create(audioUserName=username,
                                                audioName=audio_name + os.path.splitext(audio_file.name)[1],
                                                audioPath=file_path,
                                                audioUrl=file_path)
            record.save()
            # downsampling_ratio = 2
            # second = 10
            # wave_data, wave_time, f = read_part_wavefile(file_path, second, downsampling_ratio)
            # wavefile_data = []
            # for i in range(0,len(wave_time),2):
            #     cur_data = []
            #     cur_data.append((float)(round(wave_time[i],3)))
            #     cur_data.append((float)(wave_data[i]))
            #     wavefile_data.append(cur_data)
            # 这个地方不能传入double类型数据
            # result = {'code': 200, 'msg': '音频文件写入成功！', 'wave_data': wavefile_data, 'wave_path': file_path}
            result = {'code': 200, 'msg': '音频文件写入成功', 'wavId': int(record.id)}
            print(result)
            return JsonResponse(result, safe=False)
        except Exception as e:
            result = {'code': 400, 'msg': '音频文件上传失败！'}
            return JsonResponse(result)


def ReadAudio(request):
    if request.method == 'GET':
        result = {'code': 400, 'error': '读取音频方式错误'}
        return JsonResponse(result)
    else:
        try:
            id = request.POST.get('id')
            wavId = PatientRecord.objects.get(id__exact=id).wavId
            wav = AudioRecord.objects.get(id__exact=wavId)
            wavName = wav.audioName
            wavPath = os.path.join(settings.MEDIA_ROOT, wavName)
            print(wavPath)
            downsampling_ratio = 2
            second = 10
            wave_data, wave_time, f = read_part_wavefile(wavPath, second, downsampling_ratio)
            wavefile_data = []
            for i in range(0, len(wave_time), 2):
                cur_data = []
                cur_data.append((float)(round(wave_time[i], 3)))
                cur_data.append((float)(wave_data[i]))
                wavefile_data.append(cur_data)
            result = {'code': 200, 'msg': '音频文件写入成功！', 'wave_data': wavefile_data, 'wave_path': wavPath}
            return JsonResponse(result)
        except Exception as e:
            result = {'code': 200, 'msg': '读取音频文件失败'}
            return JsonResponse(result)


def ClassifyAudio(request):
    pass


def DownloadAudio(request):
    pass
